package com.example.teaculture.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.teaculture.R;
import com.example.teaculture.service.UserService;

public class LoginActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    findViews();
  }
  private EditText username;
  private EditText password;
  private Button login;
  private Button register;

  private void findViews() {
    username=(EditText) findViewById(R.id.username);
    password=(EditText) findViewById(R.id.password);
    login=(Button) findViewById(R.id.login);
    register=(Button) findViewById(R.id.register);

    login.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String name = username.getText().toString();
        System.out.println(name);
        String pass = password.getText().toString();
        System.out.println(pass);
        if (name == null || "".equals(name) || pass == null || "".equals(pass)) {
          Toast.makeText(LoginActivity.this, "账号与密码不能为空", Toast.LENGTH_SHORT).show();
        } else {
          Log.i("TAG", name + "_" + pass);
          UserService uService = new UserService(LoginActivity.this);
          boolean judge = uService.isEmail(name);
          if (judge == true) {
            boolean flag = uService.login(name, pass);

            if (flag) {
              Log.i("TAG", "登录成功");
              Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();
              Intent intent = new Intent(LoginActivity.this, MainActivity.class);
              intent.putExtra("Email",name);
              startActivity(intent);
            } else {
              Log.i("TAG", "登录失败");
              Toast.makeText(LoginActivity.this, "登录失败,邮箱或者密码错误!", Toast.LENGTH_LONG).show();
            }
          }else{
            Toast.makeText(LoginActivity.this,"输入邮箱格式不正确!",Toast.LENGTH_SHORT).show();
          }
        }
      }
    });
    register.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        Intent intent=new Intent(LoginActivity.this, RegisterActivity.class);
        startActivity(intent);
      }
    });
  }
  public void reback(View view){
    Intent intent=new Intent(LoginActivity.this,MainActivity.class);
    startActivity(intent);
  }
}
